package com.org.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.org.DTO.PageDTO;
import com.org.clients.HttpClient;
import com.org.context.BaseContext;
import com.org.entity.Region;
import com.org.exception.BaseException;
import com.org.exception.ServerException;
import com.org.mapper.RegionMapper;
import com.org.message.BaseMessage;
import com.org.result.Result;
import com.org.service.RegionService;
import com.org.vo.PageResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
@RequiredArgsConstructor
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region> implements RegionService {

    private final RegionMapper regionMapper;

    private final String COLLECTITEMS_REQUEST = "http://localhost:8080/pc/collectItems/pageFindAll";

    private final String SEARCHITEMS_REQUEST = "http://localhost:8080/pc/searchItems/pageFindAll";

    /**
     * 分页查询所有地区
     * @return
     */
    @Override
    public PageResult findRegion(PageDTO pageDTO) {
        //1.分页
        Page<Region> page = lambdaQuery()
                .page(new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize()));
        //2.构建返回结果
        PageResult pageResult = new PageResult();
        log.info("总记录数：{}", page.getTotal());
        pageResult.setTotal(page.getTotal());
        pageResult.setRows(page.getRecords());
        return pageResult;
    }

    /**
     * 修改区域
     * @param region
     * @return
     */
    @Override
    public void updateRegion(Region region) {
        region.setUpdateTime(LocalDateTime.now());
        LambdaUpdateWrapper<Region> wq = new LambdaUpdateWrapper<Region>()
                .eq(Region::getId, region.getId())
                .set(Region::getSchool, region.getSchool())
                .set(Region::getUpdateTime, region.getUpdateTime());
        regionMapper.update(region, wq);
    }

    /**
     * 添加区域
     * @param region
     */
    @Override
    public void addRegion(Region region) {
        region.setCreateTime(LocalDateTime.now());
        region.setUpdateTime(LocalDateTime.now());
        regionMapper.insert(region);
    }

    /**
     * 删除区域
     * @param id
     */
    @Override
    public void deleteRegion(Long id) {
        //1、查找该区域下的帖子(失物招领、寻物启事)
        //1.1、构造分页查询的参数
        HashMap<String,String> params = new HashMap<>();
        params.put("pageNum", "1");
        params.put("pageSize", "1000");
        params.put("regionId", id.toString());
        //1.2、查询失物招领
        int index = 0;    //索引：0表示没有数据
        String collectItemsResultString = HttpClient.doGet(COLLECTITEMS_REQUEST, params, BaseContext.getThreadLocalToken());
        //1.3、查询寻物启事
        String searchItemsResultString = HttpClient.doGet(SEARCHITEMS_REQUEST, params, BaseContext.getThreadLocalToken());
        //1.4、将String转为JSON格式
        //1.4.1、获取Result类
        Result collectItemsResult = JSON.parseObject(collectItemsResultString, Result.class);
        Result searchItemsResult = JSON.parseObject(searchItemsResultString, Result.class);
        //处理请求异常
        if(collectItemsResult.getCode() !=200 || searchItemsResult.getCode() !=200){
            log.error("分页查询失物招领、寻物启事请求失败，请检查!!!");
            throw new ServerException(BaseMessage.SERVER_ERROR);
        }
        //1.4.2、获取PageResult类的String
        String collectItemsPageResultString = collectItemsResult.getData().toString();
        String searchItemsPageResultString = searchItemsResult.getData().toString();
        //1.4.3、获取PageResult类
        PageResult collectItemsPageResult = JSON.parseObject(collectItemsPageResultString, PageResult.class);
        PageResult searchItemsPageResult = JSON.parseObject(searchItemsPageResultString, PageResult.class);
        //2、判断该区域下的帖子是否为空
        if(collectItemsPageResult.getTotal() != 0 || searchItemsPageResult.getTotal() != 0){
             index = 1;
         }
        //3、不为空，则不能删除
        if(index != 0){
            throw new BaseException(BaseMessage.REGION_DELETE_ERROR);
        }
        //4、为空，删除区域
        regionMapper.deleteById(id);
    }
}
